<?php
/**
 * Author: Hancock
 * Email: 84622365@qq.com
 * Date: 3/23/2016
 * Des: 常用函数库
 */
defined('INHkMvc') or exit('Access Invalid!');

/**
 * 控制器
 * @param $con
 * @param string $act
 * @return bool
 */
function C($con, $act = "index")
{
    $controller_path = ROOT_PATH . APP . SEPARATE . "Controller/" . ucwords($con) . "Controller.class.php";
    if (file_exists($controller_path)) {
        require_once($controller_path);
        $con = ucwords($con) . "Controller";
        if (!method_exists($con = new $con, $act . DEFAULT_ACT_SUFFIX)) {
            LD("Act: $act is missing.");
        } else {
            $act .= DEFAULT_ACT_SUFFIX;
        }
        return $con->$act();
    } else {
        LD("Controller: $con is missing.");
    }
}

/**
 * 模型
 * @param $model
 * @return bool
 */
function M($class_name, $params = [])
{
    $class_name = ucfirst(str_replace(".", "_", $class_name));
    $model_path = ROOT_PATH . APP . SEPARATE . "Model/" . $class_name . "Model.class.php";
    if (file_exists($model_path)) {
        require_once($model_path);
        $class_model = ucwords($class_name) . "Model";
        return new $class_model($params);
    } else {
        return false;
    }
}

function read_excel($file_path, $page)
{
    include_once ROOT_PATH . 'inc/doExcel.class.php';
    $excel = new doExcel;
    return $excel->readExcel($file_path, $page);
}

function getTableName($class_name, $basic_class_name)
{
    return strtolower(lcfirst(str_replace(str_replace("Model", "", $basic_class_name) . "_", '', str_replace("Model", "", $class_name))));

}

/**
 * 视图
 * @param $view
 * @return bool|string
 */
function display($tpl, $theme = '')
{
    $theme = ($theme) ? $theme : DEFAULT_THEME;
    $template = str_replace(SITE_URL, ROOT_PATH, TEMPLATE . $theme . SEPARATE . $tpl . '.php');
    if (file_exists($template)) {
        return $template;
    } else {
        LD("Template:" . $template . " is no exists");
    }
}

/**
 * 报错为了以后替换
 * @param $msg
 */
function LD($msg)
{
    if (is_array($msg)) {
        echo "<pre>";
        print_r($msg);
        die;
    } elseif (is_object($msg)) {
        var_dump($msg);
        die;
    } else {
        var_dump($msg);
        die;
    }
}

/**
 * 创建文件夹
 * @param $path
 * @param string $power
 * @param bool|false $recursive
 */
function makeDir($path, $power = 0755, $recursive = false)
{
    mkdir($path, $power, $recursive);
}

/**
 * 删除文件夹
 * @param $path
 */
function delDir($path)
{
    //先删除目录下的文件：
    $dh = opendir($path);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $full_path = $path . "/" . $file;
            if (!is_dir($full_path)) {
                unlink($full_path);
            } else {
                delDir($full_path);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹：
    if (rmdir($path)) {
        return true;
    } else {
        return false;
    }
}

function my_scandir($path, $order)
{
    $files = [];
    if (is_dir($path)) {
        if ($dir = opendir($path)) {
            while (($file = readdir($dir)) !== false) {
                if ($file != "." && $file != "..") {
                    if (is_dir($path . "/" . $file)) {
                        $files[$file] = my_scandir($path . "/" . $file, $order);
                    } else {
                        $files[] = ['file_name' => $path . "/" . $file, 'file_time' => strtotime(str_replace($order . '/', "", $path))];
                    }
                }
            }
            closedir($dir);
        }
    }
    return $files;
}

function getFilePathByTime($path, $add_time, $end_time)
{
    $time = [];
    $count = 0;
    $count = ($end_time - $add_time) / 86400 + 1;
    for ($i = 0; $i < $count; $i++) {
        $y = 0;
        $m = 0;
        $d = 0;
        $y = explode('-', date('Y-m-d', $add_time + 86400 * $i))[0];
        $m = explode('-', date('Y-m-d', $add_time + 86400 * $i))[1];
        $d = explode('-', date('Y-m-d', $add_time + 86400 * $i))[2];
        $time[] = $path . "/" . $y . "/" . $m . "/" . $d;
    }
    return $time;
}

function getSmsMobile($site_name)
{
    $data = M('vr.sms_ini')->find(['site_name' => $site_name]);
    $path = ROOT_PATH . 'data/mobile/' . $site_name . '.ini';
    if (!empty($data)) {
        if ($data['is_edit'] == 1) {
            file_put_contents($path, $data['mobile']);
            return $data['mobile'];
        } else {
            return file_get_contents($path);
        }
    } else {
        return file_get_contents($path);
    }
}

function url($con = "index", $act = "index", $params = [])
{
    if (APP == DEFAULT_APP) {
        $url = SITE_URL;
    } else {
        $url = SITE_URL . APP . SEPARATE;
    }
    if ($act == "index") {
        if ($con != "index") {
            $url .= '?con=' . $con;
        }
    } else {
        $url .= '?con=' . $con . '&act=' . $act;
    }
    foreach ($params as $key => $param) {
        if ($key != 'con' && $key != 'act') {
            $url .= '&' . $key . '=' . $param;
        }
    }
    return $url;
}

/**
 * 判断是否手机
 * @return boolean 是否手机
 */
function is_mobile()
{
    // returns true if one of the specified mobile browsers is detected
    $regex_match = "/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
    $regex_match .= "htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
    $regex_match .= "blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
    $regex_match .= "symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
    $regex_match .= "jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
    $regex_match .= ")/i";
    return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
}

/**
 * 判断是否微信
 * @return bool 是否微信
 */
function is_weixin()
{
    return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
}

/**
 * @param $data
 * @param $msg
 * @param $status
 * @return $info in json
 */
function ajaxReturn($data, $msg, $status)
{
    $info = array();
    $info['data'] = $data;
    $info['msg'] = $msg;
    $info['status'] = $status;
    if (isset($_GET['callback'])) {
        $msg = $_GET['callback'] . '(' . json_encode($info) . ')';
    } else {
        $msg = json_encode($info);
    }
    header('Content-Type:text/html; charset=utf-8');
    exit($msg);
}
/**
 * 获取IP4
 * @param int $type
 * @return mixed
 */
function get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 获取$_FILES去后缀文件名
 * @param array $files
 * @return string
 */
function getFileTrueName(array $files)
{
    unset($files[sizeof($files) - 1]);
    return implode('.', $files);
}

/**
 * MD5加密
 * @param $str
 * @return string
 */
function md5Encode($str)
{
    return md5($str . MD5_STATE);
}

/**
 * 验证MD5加密
 * @param $str
 * @param $md5_str
 * @return bool
 */
function authMd5($str, $md5_str)
{
    if (md5($str . MD5_STATE) == $md5_str) {
        return true;
    } else {
        return false;
    }
}

function createcode($len = 10)
{
    $strs = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $strlen = strlen($strs) - 1;
    $rt = '';
    for ($i = 0; $i < $len; $i++) {
        $rt .= $strs[rand(0, $strlen)];
    }
    return $rt;
}

function replaceBase64Image($jpg)
{
    $jpg = str_replace('data:image/png;base64,', '', $jpg);
    $jpg = str_replace('data:image/jpeg;base64,', '', $jpg);
    $jpg = str_replace('data:image/gif;base64,', '', $jpg);
    $jpg = str_replace('data:image/jpg;base64,', '', $jpg);
    return base64_decode($jpg);
}

/**
 * md5简易加密
 * @param $str
 * @param int $len
 * @return string
 */
function md52($str, $len = 20)
{
    $str = substr(md5($str), 3, $len);
    return $str;
}

function getFavoritesClickUrl($ad_zone_id, $fav_id, $page, $page_size = 100)
{
    include_once ROOT_PATH . "inc/ali/tbk.class.php";
    $tbk = new tbk;
    $tbk_info = $tbk->getFavoritesClickUrl($ad_zone_id, $fav_id, $page, $page_size);
    $data = objectToArray($tbk_info);
    return $data;
}

function getSpreadClickUrl($url)
{
    include_once ROOT_PATH . "inc/ali/tbk.class.php";
    $tbk = new tbk;
    $tbk_info = $tbk->getSpreadClickUrl($url);
    $data = objectToArray($tbk_info);
    return $data;

}

function objectToArray($e)
{
    $e = (array)$e;
    foreach ($e as $k => $v) {
        if (gettype($v) == 'resource') return;
        if (gettype($v) == 'object' || gettype($v) == 'array')
            $e[$k] = (array)objectToArray($v);
    }
    return $e;
}

function readExcelForAdZoneId($file_path, $page)
{
    include ROOT_PATH . 'inc/doExcel.class.php';
    $excel = new doExcel;
    return $excel->readExcelByAdZoneId($file_path, $page);
}

/**
 * @param $tel
 * @param $params ['code' => $code]
 * @param string $sms_code
 * @return array
 */
function smsSend($tel, $params, $sms_code = 'default_code')
{
    include_once LIBS_PATH . 'class' . SEPARATE . 'sms.class.php';
    $sms = new sms(0);
    return $sms->send($tel, $params, $sms_code);
}

function taobaoCurl($type, $param = [])
{
    $header = [
        "User-Agent" => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36",
        "Content-type" => "application/x-www-form-urlencoded; charset=UTF-8",
        "Host" => "pub.alimama.com",
        "Accept" => "application/json, text/javascript, */*; q=0.01",
        "Accept-Encoding" => "gzip, deflate",
        "Referer" => "http://pub.alimama.com/myunion.htm?report/site/site",
    ];

    $cookie = json_decode(file_get_contents(TAOBAO_COOKIE), 1);
    $str = "";
    foreach ($cookie as $key => $value) {
        $str .= $key . "=" . $value . ";";
    }

    if ($type == "click") {
        $url = getClickUrl($param['num_iid'], $param['ad_zone_id'], $cookie['_tb_token_'], isset($param['site_id']) ? $param['site_id'] : 18564365);
    } elseif ($type == "plan") {
        $url = getPlanUrl($param['page'], $param['page_size'], $cookie['_tb_token_']);
    } elseif ($type == "good") {
        $url = getGoodUrl($param['campaignId'], $param['shopKeeperId'], $param['userNumberId'], $param['page'], $cookie['_tb_token_']);
    } elseif ($type == "order") {
        $url = getOrderUrl($param['start_date'], $param['end_date']);
    } elseif ($type == "goods") {
        $url = getGoodsUrl($param['num_iid'], $param['perPageSize'], $param['shopTag'], $cookie['_tb_token_']);
    } elseif ($type == "goodUpdate") {
        $url = getUpdateGoodUrl($param['num_iid'], $param['perPageSize'], $param['shopTag']);
    } elseif ($type == "shop") {
        $url = getShopInfo($param['oriMemberId'], $cookie['_tb_token_']);
    } elseif ($type == "red") {
        $url = getRedPacket($param['ad_zone_id'], $cookie['_tb_token_']);
    }  elseif ($type == "adzone") {
        $url = getAdzoneId($param['to_page'], $cookie['_tb_token_']);
    } elseif($type == "title") {
        $url = getGoodsByTitle($param['title'],$param['shopTag'],$param['page_size'],$cookie['_tb_token_']);
    }else {
        return ['code' => 201, 'data' => 'bad request'];
    }

    if ($type == "goodUpdate") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //curl_setopt($ch, CURLOPT_COOKIE, $str);


        $data = curl_exec($ch);
        curl_close($ch);
        if (strstr($data, "302 Found")) {
            return "302";
        } else {
            return json_decode($data, 1);
        }
    } else {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_COOKIE, $str);


        $data = curl_exec($ch);
        curl_close($ch);
    }

    if ($type == "order") {
        return $data;
    } else {
        return json_decode($data, 1);
    }
}

function getPlanUrl($page, $page_size, $tb_token)
{
    return "http://pub.alimama.com/campaign/joinedSpecialCampaigns.json?toPage=" . $page . "&perPageSize=" . $page_size . "&_tb_token_=" . $tb_token . "&status=2&_input_charset=utf-8";
}

function getShopInfo($oriMemberId, $tb_token)
{
    return "https://pub.alimama.com/shopdetail/shopinfo.json?oriMemberId=" . $oriMemberId . "&_tb_token_=" . $tb_token . "&_input_charset=utf-8";
}

function getClickUrl($num_iid, $adzone_id, $tb_token, $site_id = '18564365')
{
//    return 'http://pub.alimama.com/common/code/getAuctionCode.json?auctionid=' . $num_iid . '&adzoneid=' . $adzone_id . '&siteid=' . $site_id . '&pvid=&_tb_token_=' . $tb_token . '&_input_charset=utf-8';
    return 'http://pub.alimama.com/common/code/getAuctionCode.json?auctionid=' . $num_iid . '&adzoneid=' . $adzone_id . '&siteid=' . $site_id . '&scenes=1&_tb_token_=' . $tb_token;
}

function getGoodUrl($campaignId, $shopKeeperId, $userNumberId, $page, $tb_token)
{
    return "http://pub.alimama.com/campaign/merchandiseDetail.json?campaignId=" . $campaignId . "&shopkeeperId=" . $shopKeeperId . "&userNumberId=" . $userNumberId . "&tab=2&omid=" . $userNumberId . "&toPage=" . $page . "&perPagesize=10&pvid=&_tb_token_=" . $tb_token . "&_input_charset=utf-8";
}

function getOrderUrl($start_data, $end_date)
{
    return "http://pub.alimama.com/report/getTbkPaymentDetails.json?queryType=1&payStatus=&DownloadID=DOWNLOAD_REPORT_INCOME_NEW&startTime=" . $start_data . "&endTime=" . $end_date;
}

function getGoodsUrl($num_iid, $perPageSize = 40, $shopTag = '', $tb_token_)
{
    return "http://pub.alimama.com/items/search.json?q=https%3A%2F%2Fitem.taobao.com%2Fitem.htm%3Fid%3D" . $num_iid . "&perPageSize=" . $perPageSize . "&shopTag=" . $shopTag . "&_tb_token_=" . $tb_token_;
}

function getUpdateGoodUrl($num_iid, $perPageSize = 40, $shopTag = '')
{
    return "http://pub.alimama.com/items/search.json?q=https%3A%2F%2Fitem.taobao.com%2Fitem.htm%3Fid%3D" . $num_iid . "&perPageSize=" . $perPageSize . "&shopTag=" . $shopTag;
}

function getRedPacket($ad_zone_id, $tb_token, $site_id = '18564365')
{
    return "https://pub.alimama.com/superCoupon/getUrlNew.json?adzoneid=" . $ad_zone_id . "&siteid=" . $site_id . "&eventId=1&_tb_token_=" . $tb_token . "&_input_charset=utf-8";
}

function getAdzoneId($to_page, $tb_token)
{
    return 'http://pub.alimama.com/common/adzone/adzoneManage.json?toPage=' . $to_page . '&perPageSize=40&gcid=0&tab=1&_tb_token_=' . $tb_token . '&_input_charset=utf-8';
}
function getGoodsByTitle($title,$shopTag='yxjh',$page_size=40,$tb_token)
{
    return 'https://pub.alimama.com/items/search.json?q='.$title.'&auctionTag=&perPageSize='.$page_size.'&shopTag='.$shopTag.'&_tb_token_='.$tb_token;
}
function getServerIp()
{
    if (isset($_SERVER)) {
        if ($_SERVER['SERVER_ADDR']) {
            $server_ip = $_SERVER['SERVER_ADDR'];
        } else {
            $server_ip = $_SERVER['LOCAL_ADDR'];
        }
    } else {
        $server_ip = getenv('SERVER_ADDR');
    }
    return $server_ip;
}
/**
 * 生成随机数
 * @param $len 随机数
 */
function createncode($len = 10)
{
    $strs = '0123456789';
    $strlen = strlen($strs) - 1;
    $rt = '';
    for ($i = 0; $i < $len; $i++) {
        $rt .= $strs[rand(0, $strlen)];
    }
    return $rt;
}
/**
 * 过滤xss攻击
 * @param str $val
 * @return mixed
 */
function removeXss($val)
{
    // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
    // this prevents some character re-spacing such as <java\0script>
    // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
    $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

    // straight replacements, the user should never need these since they're normal characters
    // this prevents like <IMG SRC=@avascript:alert('XSS')>
    $search = 'abcdefghijklmnopqrstuvwxyz';
    $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $search .= '1234567890!@#$%^&*()';
    $search .= '~`";:?+/={}[]-_|\'\\';
    for ($i = 0; $i < strlen($search); $i++) {
        // ;? matches the ;, which is optional
        // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

        // @ @ search for the hex values
        $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
        // @ @ 0{0,7} matches '0' zero to seven times
        $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
    }

    // now the only remaining whitespace attacks are \t, \n, and \r
    $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script',
        'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
    $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut',
        'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate',
        'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut',
        'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend',
        'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange',
        'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete',
        'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover',
        'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange',
        'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted',
        'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $ra = array_merge($ra1, $ra2);

    $found = true; // keep replacing as long as the previous round replaced something
    while ($found == true) {
        $val_before = $val;
        for ($i = 0; $i < sizeof($ra); $i++) {
            $pattern = '/';
            for ($j = 0; $j < strlen($ra[$i]); $j++) {
                if ($j > 0) {
                    $pattern .= '(';
                    $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                    $pattern .= '|';
                    $pattern .= '|(&#0{0,8}([9|10|13]);)';
                    $pattern .= ')*';
                }
                $pattern .= $ra[$i][$j];
            }
            $pattern .= '/i';
            $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
            $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
            if ($val_before == $val) {
                // no replacements were made, so exit the loop
                $found = false;
            }
        }
    }
    return $val;
}

function getHostIp()
{
    $file = ROOT_PATH . 'ip.ini';
    if (file_exists($file)) {
        $ip = file_get_contents($file);
    } else {
        $ip = trim(file_get_contents("http://newtc.720baba.com/?con=api&act=getIp"));
        file_put_contents($file, $ip);
    }
    return $ip;
}
function getShortClickUrlByUrl($click_url, $site_name = ALI_APP_KEY)
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $data = objectToArray($collectUrl->getSpreadClickUrlByUrl($click_url));
    if ($data['total_results'] > 0) {
        if ($data['results']['tbk_spread']['err_msg'] == 'OK') {
            return $data['results']['tbk_spread']['content'];
        } else {
            return false;
        }
    } else {
        return false;
    }
}
function getShareTpwd($logo, $title, $click_url, $site_name = ALI_APP_KEY)
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $shareTpwd = $collectUrl->getShareTpwd($logo, $title, $click_url);
    $shareTpwd = objectToArray($shareTpwd)['model'];
    if ($shareTpwd == false) {
        return false;
    } else {
        if (preg_match("/^(￥|《).*(￥|《)$/", $shareTpwd)) {
            if (preg_match("/^(《).*(《)$/", $shareTpwd)) {
                $shareTpwd = str_replace('《', '￥', $shareTpwd);
            } else {
                $shareTpwd = $shareTpwd;
            }
        } else {
            return false;
        }
        return $shareTpwd;
    }
}
function getClick($num_iid, $ad_zone_id, $site_name, $site_id)
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $ip = $collectUrl->getTbIpBySiteName();
    $curlPost = [
        'num_iid' => $num_iid,
        'ad_zone_id' => $ad_zone_id,
        'site_id' => $site_id
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://' . $ip . '/vr_crm/?con=api&act=getClick');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    $url = json_decode($data, 1);
    return $url['data'];
}
function getGoodByTitle($title,$shopTag='yxjh',$page=1,$page_size=40)
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $ip = $collectUrl->getTbIpBySiteName();
    $curlPost = [
        'title' => $title,
        'shopTag' => $shopTag,
        'page' => $page,
        'page_size' => $page_size
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://crm.720baba.com/?con=api&act=getGoodsByTitle');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    $url = json_decode($data, 1);
    return $url['data'];
}
function distributionAdZoneId($member_id, $site_name = ALI_APP_KEY)
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $ad_zone_id = $collectUrl->distributionAdZoneId($member_id);
    return $ad_zone_id;
}
function getNumiidByTbkPass($tbk_pass)
{
    $site_data = M('app.ali_app')->getAllSiteName();
    if (empty($site_data)) {
        return false;
    }
    $i = 0;
    while ($i < count($site_data)) {
        $url = getNumiidByTbkPassBySite($tbk_pass, $site_data[$i]['app']);
        if (!empty($url)) {
            break;
        } else {
            $i++;
        }
        if ($i >= count($site_data)) {
            return false;
        }
    }
    return $url;
}
function getNumiidByTbkPassBySite($tbk_pass, $site_name = ALI_APP_KEY)
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $data = objectToArray($collectUrl->getNumiidByTbkPass($tbk_pass));
    if (!empty($data['url'])) {
        return $data['url'];
    } else {
        return false;
    }
}
function getGoodsUrlForCapp($num_iid)
{
    $site_data = M('app.ali_app')->getAllSiteName();
    if (empty($site_data)) {
        return false;
    }
    $i = 0;
    while ($i < count($site_data)) {
        $data = getGoodsUrlBySite($num_iid, $site_data[$i]['app']);
        if (!empty($data['data']['pageList']) && isset($data['data']['pageList'])) {
            break;
        } else {
            $i++;
        }
        if ($i >= count($site_data)) {
            return false;
        }
    }
    return $data;
}
function getGoodsUrlBySite($num_iid, $site_name = ALI_APP_KEY, $perPageSize = 40, $shopTag = '-1')
{
    include_once ROOT_PATH . 'inc/collectUrl.class.php';
    $collectUrl = new collectUrl($site_name);
    $ip = $collectUrl->getTbIpBySiteName();
    $curlPost = 'num_iid=' . $num_iid . '&perPageSize=' . $perPageSize . '&shopTag=' . $shopTag;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://' . $ip . '/vr_crm/?con=api&act=getGoodsUrl');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    $url = json_decode($data, 1);
    return $url['data'];
}
function getOwnerGood($num_iid)
{
    $curlPost = 'num_iid=' . $num_iid;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://crm.720baba.com/?con=Sp&act=getGoodInfo');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);
    curl_close($ch);
    $url = (array)json_decode($data);
    $url = objectToArray($url);
    return $url['data'];
}
